﻿using System;
using System.Windows;
using System.Windows.Controls;
using Nomad.WebSync.Extensions;
using System.Windows.Input;

namespace Nomad.WebSync.Windows.Forms {
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Page {
        /// <summary>
        /// Creates a new instance of Login class
        /// </summary>
        public Login() {
            InitializeComponent();
        }

        private void executeLogin() {
            using (var service = new WebSyncService.Desktop()) {
                var result = service.Login(usernameTextBox.Text, passwordTextBox.Password.Encrypt());
                if (string.IsNullOrEmpty(result))
                    throw new Exception("Invalid Login");

                App.WebSyncHeader = new WebSyncService.WebSyncHeader();
                App.WebSyncHeader.Session = result;

                NavigationService.Navigate(null);
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                App.Current.Shutdown();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void loginButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.executeLogin();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
    }
}
